<template>
  <div>
    <el-dialog :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" :rules="rules" class="add-user-row">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户账号" prop="username" :label-width="formLabelWidth" required>
              <el-input v-model="form.username" autocomplete="off" placeholder="请输入用户账号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="chineseName" :label-width="formLabelWidth" required>
              <el-input v-model="form.chineseName" autocomplete="off" placeholder="请输入用户姓名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="isAdd">
          <el-col :span="12">
            <el-form-item label="密码" prop="password" :label-width="formLabelWidth" required>
              <el-input v-model="form.password" autocomplete="off" placeholder="请输入密码6位以上" show-password />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="conformPassword" :label-width="formLabelWidth" required>
              <el-input v-model="form.conformPassword" autocomplete="off" placeholder="请输入密码6位以上" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="tel" :label-width="formLabelWidth" required>
              <el-input v-model="form.tel" autocomplete="off" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="帐号状态" :label-width="formLabelWidth">
              <el-switch
                v-model="form.dataStatus"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer add-user-btn1">
        <el-row>
          <el-col :span="24">
            <el-button @click="definedClose()">取 消</el-button>
            <el-button v-if="isAddOrSave" type="primary" @click="submit('form')">创建</el-button>
            <el-button v-if="isSave" type="primary" @click="submit('form')">保存</el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addUser, updateUser } from '../../../api/user'

const form = {
  chineseName: '',
  username: '',
  tel: '',
  dataStatus: '1',
  password: '',
  conformPassword: ''
}

export default {
  data() {
    // 密码验证
    const checkPassword = (rule, value, callback) => {
      value = value.replace(/\s/g, '')
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value.length < 6) {
        callback(new Error('密码不能小于6位'))
      } else {
        if (this.form.conformPassword !== '') {
          this.$refs.form.validateField('conformPassword')
        }
        callback()
      }
    }
    const checkConformPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    // 电话号码验证
    const checkTel = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 100)
    }

    return {
      dialogFormVisible: false,
      form: JSON.parse(JSON.stringify(form)),
      formLabelWidth: '100px',
      isAdd: false,
      isSave: false,
      isAddOrSave: false,
      rules: {
        tel: [
          { validator: checkTel, trigger: ['change', 'blur'] }
        ],
        username: [
          { required: true, message: '请输入账号', trigger: ['change', 'blur'] },
          { min: 3, message: '长度不能小于3位', trigger: ['change', 'blur'] }
        ],
        chineseName: [
          { required: true, message: '请输入用户名', trigger: ['change', 'blur'] },
          { min: 2, message: '长度不能小于2位', trigger: ['change', 'blur'] }
        ],
        password: [
          { validator: checkPassword, trigger: ['change', 'blur'] }
        ],
        conformPassword: [
          { validator: checkConformPassword, trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  mounted() {
    this.$bus.on('usersDialog', (obj) => {
      this.originObj = obj
      this.isAdd = obj.isAdd
      this.isSave = obj.isSave
      this.isAddOrSave = obj.isAddOrSave
      if (!obj.isAdd) {
        obj.dataStatus = obj.dataStatus + ''
        this.form = obj
      } else {
        console.log(this.form)
        this.submitSuccess()
        console.log(this.form)
      }
      this.dialogFormVisible = true
    })
  },
  methods: {
    submit: function(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.originObj.isAdd) {
            addUser(this.form).then(res => {
              this.$message({
                message: '恭喜你，创建用户成功！',
                type: 'success'
              })
              this.submitSuccess()
              this.clearRules(form)
            })
          } else if (this.originObj.isSave) {
            updateUser(this.form).then(res => {
              this.$message({
                message: '编辑完成！',
                type: 'success'
              })
              this.submitSuccess()
              this.clearRules(form)
              console.log(this.form)
            })
          }
        } else {
          console.log('提交失败')
          return false
        }
      })
    },
    submitSuccess() {
      typeof this.originObj.successFn === 'function' && this.originObj.successFn()
      // 从form对象中解析出字符串然后解析成josn格式
      // this.form = JSON.parse(JSON.stringify(form))
    },
    clearRules(form) {
      this.dialogFormVisible = false
      this.$refs[form].resetFields()
    },
    definedClose() {
      this.dialogFormVisible = false
    }
  }
}
</script>
<style lang="scss" scoped>
  .dialog-footer{
    &.add-user-btn1{
      text-align: right;
    }
  }
</style>

